package com.rbac.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rbac.common.Result;
import com.rbac.entity.SysMenu;
import com.rbac.service.SysMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 菜单管理控制器
 *
 * @author rbac-system
 * @since 2024-01-01
 */
@RestController
@RequestMapping("/menu")
@Api(tags = "菜单管理")
public class SysMenuController {

    @Autowired
    private SysMenuService menuService;

    @GetMapping("/page")
    @ApiOperation("分页查询菜单")
    @PreAuthorize("hasAuthority('menu:query')")
    public Result<IPage<SysMenu>> page(
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer current,
            @ApiParam("每页大小") @RequestParam(defaultValue = "10") Integer size,
            @ApiParam("菜单名称") @RequestParam(required = false) String menuName,
            @ApiParam("菜单编码") @RequestParam(required = false) String menuCode,
            @ApiParam("菜单类型") @RequestParam(required = false) Integer menuType,
            @ApiParam("状态") @RequestParam(required = false) Integer status) {
        
        Page<SysMenu> page = new Page<>(current, size);
        IPage<SysMenu> result = menuService.page(page, menuName, menuCode, menuType, status);
        return Result.success(result);
    }

    @GetMapping("/list")
    @ApiOperation("查询菜单列表")
    @PreAuthorize("hasAuthority('menu:query')")
    public Result<List<SysMenu>> list() {
        List<SysMenu> list = menuService.list();
        return Result.success(list);
    }

    @GetMapping("/tree")
    @ApiOperation("查询菜单树")
    @PreAuthorize("hasAuthority('menu:query')")
    public Result<List<SysMenu>> tree() {
        List<SysMenu> tree = menuService.getMenuTree();
        return Result.success(tree);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据ID查询菜单")
    @PreAuthorize("hasAuthority('menu:query')")
    public Result<SysMenu> getById(@ApiParam("菜单ID") @PathVariable Long id) {
        SysMenu menu = menuService.getById(id);
        if (menu == null) {
            return Result.error("菜单不存在");
        }
        return Result.success(menu);
    }

    @PostMapping
    @ApiOperation("创建菜单")
    @PreAuthorize("hasAuthority('menu:add')")
    public Result<String> create(@Valid @RequestBody SysMenu menu) {
        // 检查菜单编码是否已存在
        if (menuService.existsByMenuCode(menu.getMenuCode())) {
            return Result.error("菜单编码已存在");
        }
        
        boolean success = menuService.save(menu);
        return success ? Result.success("创建成功") : Result.error("创建失败");
    }

    @PutMapping("/{id}")
    @ApiOperation("更新菜单")
    @PreAuthorize("hasAuthority('menu:edit')")
    public Result<String> update(@ApiParam("菜单ID") @PathVariable Long id, @Valid @RequestBody SysMenu menu) {
        menu.setId(id);
        
        // 检查菜单编码是否被其他菜单使用
        if (menuService.existsByMenuCodeAndIdNot(menu.getMenuCode(), id)) {
            return Result.error("菜单编码已被其他菜单使用");
        }
        
        boolean success = menuService.updateById(menu);
        return success ? Result.success("更新成功") : Result.error("更新失败");
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除菜单")
    @PreAuthorize("hasAuthority('menu:delete')")
    public Result<String> delete(@ApiParam("菜单ID") @PathVariable Long id) {
        boolean success = menuService.removeById(id);
        return success ? Result.success("删除成功") : Result.error("删除失败");
    }

    @GetMapping("/role/{roleId}")
    @ApiOperation("查询角色菜单")
    @PreAuthorize("hasAuthority('menu:query')")
    public Result<List<SysMenu>> getMenusByRoleId(@ApiParam("角色ID") @PathVariable Long roleId) {
        List<SysMenu> menus = menuService.getMenusByRoleId(roleId);
        return Result.success(menus);
    }

    @GetMapping("/user/{userId}")
    @ApiOperation("查询用户菜单")
    @PreAuthorize("hasAuthority('menu:query')")
    public Result<List<SysMenu>> getMenusByUserId(@ApiParam("用户ID") @PathVariable Long userId) {
        List<SysMenu> menus = menuService.getMenusByUserId(userId);
        return Result.success(menus);
    }
}
